package com.ttx.pattern.example.state.after;

import com.ttx.pattern.example.state.after.states.HasQuarterSate;
import com.ttx.pattern.example.state.after.states.NoQuarterSate;
import com.ttx.pattern.example.state.after.states.SoldOutState;
import com.ttx.pattern.example.state.after.states.SoldState;

/**
 * 糖果机
 *   (各状态的上下文, 可获取各个状态)
 * @author TimFruit
 * @date 2019/5/19 13:40
 */

public class GumballMachine{
    
    // --------------------------------- 糖果机对应的各个状态
    private State soldState;
    private State soldOutState;
    private State noQuarterState;
    private State hasQuarterState;
    // ----------------------------------

    
    /**
     * 糖果机当前的状态
     */
    private State currState;
    
    /**
     * 糖果数
     */
    private int count=0;

    public GumballMachine(int gumballCount) {
        this.count = gumballCount;

        this.soldState=new SoldState(this);
        this.soldOutState=new SoldOutState(this);
        this.noQuarterState=new NoQuarterSate(this);
        this.hasQuarterState=new HasQuarterSate(this);
        
        if(this.count<=0){
            this.currState=this.soldOutState;  
        }else {
            this.currState=this.noQuarterState;  //刚开始是没有投硬币
        }
    }

    
    
    // ------------------------------------------------
    // 糖果机对外暴露的行为， 内部委托给对应的状态处理
    // ------------------------------------------------
    
    public void insertQuarter() { //客人投入硬币
        this.currState.insertQuarter();
    }

    public void ejectQuarter() { //退出硬币
        this.currState.ejectQuarter();
    }

    public void turnCrank() {
        this.currState.turnCrank(); //客人转动曲柄
        this.currState.dispense();  //发放糖果
    }


    

    // ------------------------------
    // setter
    // ------------------------------

    public void setCurrState(State currState) {
        this.currState = currState;
    }

    public void setCount(int count) {
        this.count = count;
    }

    // -----------------------------
    // getter
    // -----------------------------

    public State getSoldState() {
        return soldState;
    }

    public State getSoldOutState() {
        return soldOutState;
    }

    public State getNoQuarterState() {
        return noQuarterState;
    }

    public State getHasQuarterState() {
        return hasQuarterState;
    }

    public State getCurrState() {
        return currState;
    }

    public int getCount() {
        return count;
    }

    
    // ----------------------------

    @Override public String toString() {
        return "糖果机还有"+this.count+"颗糖果";
    }
}
